{% extends "base.html" %}

{% block content %}
<div class="card">
    <h2><i class="fas fa-file-alt"></i> 医学模拟考试</h2>
    <p>模拟真实医学考试环境，测试您的知识掌握程度。</p>
    
    <div class="exam-info">
        <div class="exam-stats">
            <span><i class="fas fa-question-circle"></i> 题目: <span id="current-question">1</span>/{{ questions|length }}</span>
            <span><i class="fas fa-clock"></i> 剩余时间: <span id="timer">30:00</span></span>
            <span><i class="fas fa-check-circle"></i> 已回答: <span id="answered">0</span></span>
        </div>
    </div>
    
    <div id="exam-container">
        <form id="exam-form">
            {% for question in questions %}
            <div class="exam-question" id="question-{{ loop.index }}" {% if loop.index != 1 %}style="display: none;"{% endif %}>
                <div class="question-header">
                    <h3>题目 {{ loop.index }}</h3>
                    <p>{{ question.question }}</p>
                </div>
                
                <div class="question-options">
                    {% for option in question.options %}
                    <div class="option">
                        <input type="radio" id="q{{ question.id }}-option{{ loop.index }}" 
                               name="q{{ question.id }}" value="{{ option }}"
                               data-question-id="{{ question.id }}">
                        <label for="q{{ question.id }}-option{{ loop.index }}">{{ option }}</label>
                    </div>
                    {% endfor %}
                </div>
                
                <div class="question-navigation">
                    {% if loop.index > 1 %}
                    <button type="button" class="btn btn-prev" data-prev="{{ loop.index - 1 }}">
                        <i class="fas fa-arrow-left"></i> 上一题
                    </button>
                    {% endif %}
                    
                    {% if loop.index < questions|length %}
                    <button type="button" class="btn btn-next" data-next="{{ loop.index + 1 }}">
                        下一题 <i class="fas fa-arrow-right"></i>
                    </button>
                    {% else %}
                    <button type="button" class="btn btn-submit" id="submit-exam">
                        <i class="fas fa-paper-plane"></i> 提交试卷
                    </button>
                    {% endif %}
                    
                    <button type="button" class="btn btn-flag" data-question="{{ loop.index }}">
                        <i class="far fa-flag"></i> 标记题目
                    </button>
                </div>
            </div>
            {% endfor %}
        </form>
    </div>
    
    <div class="question-progress">
        <h4>题目导航</h4>
        <div class="progress-buttons">
            {% for question in questions %}
            <button type="button" class="progress-btn {% if loop.index == 1 %}active{% endif %}" 
                    data-question="{{ loop.index }}">
                {{ loop.index }}
            </button>
            {% endfor %}
        </div>
    </div>
</div>

<div id="result-modal" class="modal">
    <div class="modal-content">
        <span class="close-modal">&times;</span>
        <h2>考试结果</h2>
        <div class="result-summary">
            <p>总分: <span id="total-score">0</span>/{{ questions|length }}</p>
            <p>正确率: <span id="accuracy">0</span>%</p>
            <p>用时: <span id="time-used">0:00</span></p>
        </div>
        <div class="result-details">
            <h3>题目解析</h3>
            <div id="question-results"></div>
        </div>
        <button class="btn" id="review-exam">复习错题</button>
    </div>
</div>

<style>
.exam-info {
    background: var(--light-color);
    padding: 1rem;
    border-radius: 8px;
    margin-bottom: 1.5rem;
}

.exam-stats {
    display: flex;
    justify-content: space-between;
}

.exam-stats span {
    font-weight: 500;
    color: var(--dark-color);
}

.exam-question {
    background: white;
    padding: 1.5rem;
    border-radius: 8px;
    box-shadow: 0 2px 10px rgba(0,0,0,0.1);
    margin-bottom: 1.5rem;
}

.question-header h3 {
    color: var(--primary-color);
    margin-bottom: 0.5rem;
}

.question-options {
    margin: 1.5rem 0;
}

.option {
    margin-bottom: 0.8rem;
    padding: 0.8rem;
    border: 1px solid #ddd;
    border-radius: 4px;
    transition: all 0.3s;
}

.option:hover {
    background: #f5f5f5;
    border-color: var(--primary-color);
}

.option input[type="radio"] {
    margin-right: 0.8rem;
}

.question-navigation {
    display: flex;
    justify-content: space-between;
    margin-top: 1.5rem;
}

.btn-prev {
    background: var(--light-color);
    color: var(--dark-color);
}

.btn-next {
    background: var(--primary-color);
    color: white;
}

.btn-submit {
    background: var(--success-color);
    color: white;
}

.btn-flag {
    background: var(--warning-color);
    color: white;
}

.question-progress {
    background: white;
    padding: 1.5rem;
    border-radius: 8px;
    box-shadow: 0 2px 10px rgba(0,0,0,0.1);
}

.progress-buttons {
    display: flex;
    flex-wrap: wrap;
    gap: 0.5rem;
    margin-top: 1rem;
}

.progress-btn {
    width: 40px;
    height: 40px;
    border-radius: 50%;
    border: 1px solid #ddd;
    background: white;
    cursor: pointer;
    transition: all 0.3s;
}

.progress-btn:hover {
    background: var(--light-color);
}

.progress-btn.active {
    background: var(--primary-color);
    color: white;
    border-color: var(--primary-color);
}

.progress-btn.flagged {
    background: var(--warning-color);
    color: white;
    border-color: var(--warning-color);
}

.progress-btn.answered {
    background: var(--success-color);
    color: white;
    border-color: var(--success-color);
}

/* 模态框样式 */
.modal {
    display: none;
    position: fixed;
    z-index: 1000;
    left: 0;
    top: 0;
    width: 100%;
    height: 100%;
    background-color: rgba(0,0,0,0.5);
}

.modal-content {
    background-color: white;
    margin: 5% auto;
    padding: 2rem;
    border-radius: 8px;
    width: 80%;
    max-width: 800px;
    max-height: 80vh;
    overflow-y: auto;
}

.close-modal {
    color: #aaa;
    float: right;
    font-size: 28px;
    font-weight: bold;
    cursor: pointer;
}

.close-modal:hover {
    color: black;
}

.result-summary {
    display: flex;
    justify-content: space-around;
    margin: 1.5rem 0;
    padding: 1rem;
    background: var(--light-color);
    border-radius: 8px;
}

.result-summary p {
    font-size: 1.2rem;
    font-weight: bold;
}

.question-result {
    margin-bottom: 1.5rem;
    padding: 1rem;
    border-radius: 8px;
}

.question-result.correct {
    background: #e8f5e9;
    border-left: 4px solid var(--success-color);
}

.question-result.incorrect {
    background: #ffebee;
    border-left: 4px solid var(--danger-color);
}

.question-result h4 {
    margin-bottom: 0.5rem;
}

.question-result p {
    margin-bottom: 0.5rem;
}

@media (max-width: 768px) {
    .exam-stats {
        flex-direction: column;
        gap: 0.5rem;
    }
    
    .question-navigation {
        flex-wrap: wrap;
        gap: 0.5rem;
    }
    
    .modal-content {
        width: 95%;
        margin: 2% auto;
    }
}
</style>

<script>
// 考试计时器
let examTime = 30 * 60; // 30分钟
const timer = document.getElementById('timer');
let timerInterval = setInterval(updateTimer, 1000);

function updateTimer() {
    const minutes = Math.floor(examTime / 60);
    const seconds = examTime % 60;
    timer.textContent = `${minutes}:${seconds < 10 ? '0' : ''}${seconds}`;
    
    if (examTime <= 0) {
        clearInterval(timerInterval);
        submitExam();
    } else {
        examTime--;
    }
}

// 题目导航
const progressButtons = document.querySelectorAll('.progress-btn');
progressButtons.forEach(button => {
    button.addEventListener('click', function() {
        const questionNum = this.getAttribute('data-question');
        showQuestion(questionNum);
        updateActiveButton(questionNum);
    });
});

// 显示指定题目
function showQuestion(questionNum) {
    document.querySelectorAll('.exam-question').forEach(question => {
        question.style.display = 'none';
    });
    document.getElementById(`question-${questionNum}`).style.display = 'block';
    document.getElementById('current-question').textContent = questionNum;
}

// 更新活跃的导航按钮
function updateActiveButton(questionNum) {
    progressButtons.forEach(button => {
        button.classList.remove('active');
        if (button.getAttribute('data-question') === questionNum) {
            button.classList.add('active');
        }
    });
}

// 上一题/下一题按钮
document.querySelectorAll('.btn-prev').forEach(button => {
    button.addEventListener('click', function() {
        const prevQuestion = this.getAttribute('data-prev');
        showQuestion(prevQuestion);
        updateActiveButton(prevQuestion);
    });
});

document.querySelectorAll('.btn-next').forEach(button => {
    button.addEventListener('click', function() {
        const nextQuestion = this.getAttribute('data-next');
        showQuestion(nextQuestion);
        updateActiveButton(nextQuestion);
    });
});

// 标记题目
document.querySelectorAll('.btn-flag').forEach(button => {
    button.addEventListener('click', function() {
        const questionNum = this.getAttribute('data-question');
        const progressBtn = document.querySelector(`.progress-btn[data-question="${questionNum}"]`);
        
        if (progressBtn.classList.contains('flagged')) {
            progressBtn.classList.remove('flagged');
            this.innerHTML = '<i class="far fa-flag"></i> 标记题目';
        } else {
            progressBtn.classList.add('flagged');
            this.innerHTML = '<i class="fas fa-flag"></i> 已标记';
        }
    });
});

// 记录已回答的题目
const examForm = document.getElementById('exam-form');
examForm.addEventListener('change', function(e) {
    if (e.target.type === 'radio') {
        const questionId = e.target.getAttribute('data-question-id');
        const progressBtn = document.querySelector(`.progress-btn[data-question="${questionId}"]`);
        
        if (!progressBtn.classList.contains('answered')) {
            progressBtn.classList.add('answered');
            updateAnsweredCount();
        }
    }
});

function updateAnsweredCount() {
    const answeredCount = document.querySelectorAll('.progress-btn.answered').length;
    document.getElementById('answered').textContent = answeredCount;
}

// 提交考试
document.getElementById('submit-exam').addEventListener('click', submitExam);

function submitExam() {
    clearInterval(timerInterval);
    
    // 收集所有答案
    const formData = new FormData(examForm);
    const answers = {};
    for (let [key, value] of formData.entries()) {
        const questionId = key.substring(1); // 去掉前面的'q'
        answers[questionId] = value;
    }
    
    // 发送答案到服务器评估
    fetch('/assessment', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
        },
        body: JSON.stringify(answers)
    })
    .then(response => response.json())
    .then(results => {
        displayResults(results);
    });
}

// 显示考试结果
function displayResults(results) {
    const modal = document.getElementById('result-modal');
    const closeModal = document.querySelector('.close-modal');
    const questionResults = document.getElementById('question-results');
    
    // 计算总分和正确率
    const correctCount = results.filter(r => r.correct).length;
    const totalQuestions = results.length;
    const accuracy = Math.round((correctCount / totalQuestions) * 100);
    
    document.getElementById('total-score').textContent = correctCount;
    document.getElementById('accuracy').textContent = accuracy;
    document.getElementById('time-used').textContent = timer.textContent;
    
    // 显示每道题的结果
    questionResults.innerHTML = '';
    results.forEach(result => {
        const resultDiv = document.createElement('div');
        resultDiv.className = `question-result ${result.correct ? 'correct' : 'incorrect'}`;
        
        resultDiv.innerHTML = `
            <h4>题目 ${result.question_id}</h4>
            <p>您的答案: ${result.user_answer}</p>
            <p>${result.explanation}</p>
        `;
        
        questionResults.appendChild(resultDiv);
    });
    
    // 显示模态框
    modal.style.display = 'block';
    
    // 关闭模态框
    closeModal.addEventListener('click', function() {
        modal.style.display = 'none';
    });
    
    window.addEventListener('click', function(event) {
        if (event.target === modal) {
            modal.style.display = 'none';
        }
    });
    
    // 复习错题按钮
    document.getElementById('review-exam').addEventListener('click', function() {
        modal.style.display = 'none';
        // 这里可以添加复习错题的逻辑
        alert('错题复习功能将在后续版本中实现');
    });
}
</script>
{% endblock %}